package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"time"
	"zhihu/models"

	"zhihu/zhihu_rpc/internal/svc"
	"zhihu/zhihu_rpc/zhihu_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type TroubleListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTroubleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TroubleListLogic {
	return &TroubleListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *TroubleListLogic) TroubleList(in *zhihu_rpc.TroubleListRequest) (*zhihu_rpc.TroubleListResponse, error) {
	// todo: add your logic here and delete this line
	var troubles []models.Trouble
	var total int
	var data []*zhihu_rpc.FromTroubleList
	var ret zhihu_rpc.TroubleListResponse
	key := fmt.Sprintf("from trouble order = %s;page = %d;title = %s", in.Order, in.Page, in.Title)
	get, _ := models.RDB.Get(models.Ctx, key).Result()
	if get == "" {
		sql := models.DB.Debug().Limit(10).Offset(int(in.Page-1) * 10).Model(&models.Trouble{})
		tsql := models.DB
		if in.Order != "" {
			sql = sql.Order(in.Order + " desc")
			tsql = tsql.Order(in.Order + " desc")
		} else {
			sql = sql.Order("hot desc")
		}
		if in.Title != "" {
			sql = sql.Where("title like ?", "%"+in.Title+"%")
			tsql = tsql.Where("title like ?", "%"+in.Title+"%")
		}
		tsql.Model(&models.Trouble{}).Pluck("count(*)", &total)
		sql.Select("troubles.*").Scan(&troubles)
		for _, t := range troubles {
			_get := zhihu_rpc.FromTroubleList{
				Id:    int64(t.UserId),
				Title: t.Title,
				Des:   t.Content,
				Hot:   int64(t.Hot),
			}
			data = append(data, &_get)
		}
		set, _ := json.Marshal(&zhihu_rpc.TroubleListResponse{
			Troubles: data,
			Total:    int64(total),
		})
		models.RDB.Set(models.Ctx, key, set, 24*time.Hour)
		ret.Troubles = data
		ret.Total = int64(total)
	} else {
		json.Unmarshal([]byte(get), &ret)
	}
	return &ret, nil
}
